package models

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"goods_srv/appconfig"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func Init() {
	var err error

	mysqlConf := appconfig.AppConf.Mysql

	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlConf.User, mysqlConf.Password, mysqlConf.Host, mysqlConf.Port, mysqlConf.Database)

	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("MySQL连接失败" + err.Error())
	} else {
		logx.Info("MySQL连接成功")
	}

	err = DB.AutoMigrate()
	if err != nil {
		panic(err)
	} else {
		logx.Info("数据库表迁移成功")
	}
}
